#include "configimpactdetector.h"
#include "systemconfig.h"
#include <QDir>
#include <QDebug>

ConfigImpactDetector::RebuildRequirement ConfigImpactDetector::analyzeConfigChange(
    const SystemConfig& oldConfig,
    const SystemConfig& newConfig)
{
    bool dpiChanged = isDPIChanged(oldConfig, newConfig);
    bool cachePathChanged = isCacheDirectoryChanged(oldConfig, newConfig);

    RebuildType rebuildType = RebuildType::None;
    QString reason;

    if (dpiChanged && cachePathChanged) {
        rebuildType = RebuildType::Both;
        reason = "DPI设置和缓存目录都已变更";
    } else if (cachePathChanged) {
        rebuildType = RebuildType::CacheDirectory;
        reason = "缓存目录已变更";
    } else if (dpiChanged) {
        rebuildType = RebuildType::DPIOnly;
        reason = "DPI设置已变更";
    }

    if (rebuildType != RebuildType::None) {
    } else {
    }

    return RebuildRequirement(rebuildType, reason);
}

bool ConfigImpactDetector::isDPIChanged(const SystemConfig& oldConfig, const SystemConfig& newConfig)
{
    if (oldConfig.processingQuality != newConfig.processingQuality) {
        double oldDpi = ConfigStrategyCalculator::calculateDpiForQuality(oldConfig.processingQuality);
        double newDpi = ConfigStrategyCalculator::calculateDpiForQuality(newConfig.processingQuality);


        // DPI差异大于5%认为需要重建缓存
        double dpiChangeRatio = qAbs(newDpi - oldDpi) / oldDpi;
        if (dpiChangeRatio > 0.05) { // 5%阈值
            return true;
        }
    }
    return false;
}

bool ConfigImpactDetector::isCacheDirectoryChanged(const SystemConfig& oldConfig, const SystemConfig& newConfig)
{
    QString oldCacheDir = oldConfig.cacheDirectory;
    QString newCacheDir = newConfig.cacheDirectory;

    if (oldCacheDir != newCacheDir) {

        // 检查旧缓存目录是否存在且有内容
        QDir oldDir(oldCacheDir);
        if (oldDir.exists() && oldDir.entryList(QDir::Files).size() > 0) {
            return true;
        }
    }
    return false;
}

QString ConfigImpactDetector::buildChangeReason(bool dpiChanged, bool cachePathChanged)
{
    QStringList reasons;

    if (dpiChanged) {
        reasons << QString("DPI设置已变更");
    }

    if (cachePathChanged) {
        reasons << QString("缓存目录已变更");
    }

    return reasons.join("；");
}